﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace PostgreSQL
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            timer1.Enabled = true;
            timer1.Start();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            try
            {
                DoSth();
            }
            catch (Exception ex)
            {
                //保存异常日志
                using (ModelsQi.TemperatureMatrixContext db = new ModelsQi.TemperatureMatrixContext())
                {
                    ModelsQi.ErrorLog log = new ModelsQi.ErrorLog();
                    log.Msg = ex.Message;
                    log.OmegaTime = DateTime.Now;

                    db.ErrorLogs.Add(log);
                    db.SaveChanges();
                }


            }
        }

        private void DoSth()
        {
            DateTime dt1 = DateTime.Now;

            int data_count = 0;
            using (Models.dbembedContext db = new Models.dbembedContext())
            {
                var data = db.Irdata.OrderByDescending(o => o.Id).Take(2).ToList();

                label_time.Text = data[0].CreatedOn.ToString("yyyy-MM-dd HH:mm:ss fff");
                label_Temp.Text = data[0].MaxTemp.ToString();
                textBox1.Text = data[0].DataIr;
                data_count = data[0].DataIr.Split(',').Length;

                DateTime dt2 = DateTime.Now;

                TimeSpan ts = dt2 - dt1;

                label1.Text = $"查询耗时：{ts.TotalMilliseconds}ms；单行数据总量：{data_count}";

                using (ModelsQi.TemperatureMatrixContext dbqi = new ModelsQi.TemperatureMatrixContext())
                {
                    ModelsQi.TestDatum tempRow = new ModelsQi.TestDatum();
                    tempRow.OmegaTime = DateTime.Now;
                    tempRow.CreatedOn = data[0].CreatedOn;
                    tempRow.MaxTemp = data[0].MaxTemp;
                    tempRow.DataIr = data[0].DataIr;

                    tempRow.ChaXunYongShiMs = ts.TotalMilliseconds;
                    tempRow.DataLength = data_count;

                    dbqi.TestData.Add(tempRow);
                    dbqi.SaveChanges();
                }
            }
           
        }

        private void button2_Click(object sender, EventArgs e)
        {
            timer1.Enabled = false;
            timer1.Stop();
        }

        private void button3_Click(object sender, EventArgs e)
        {
            Form2 f2 = new Form2();
            f2.Show();

            
        }
    }
}
